﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using System.Web.Script.Serialization;
using DVK.SP2007;

namespace DVK.SP2007.Moss
{
    /// <summary>
    /// Future info and reasoning:
    /// This class is separate because it can only be used by MOSS system. 
    /// Somekind of dependency injection container should be used to initialize correct container and correct
    /// UserInfo object in SendToDvk page (or other locations) based on configuration in DVKSettings.
    /// 
    /// Right now, we have direct reference from Dvk.SP2007 project!
    /// This however makes it not work with WSS.
    /// </summary>
    public class MossUserInfoManager : IUserInfoManager<string>
    {
        IMapping _mapping;
        UserProfileManager _userProfileManager;

        /// <summary>
        /// Initializes a new instance of the <see cref="MossUserInfoManager"/> class.
        /// </summary>
        /// <param name="mapping">The mapping.</param>
        public MossUserInfoManager(IMapping mapping)
        {
            _mapping = mapping;
            _userProfileManager = new UserProfileManager(ServerContext.Current);
        }

        #region IUserInfoManager Members

        /// <summary>
        /// Gets the user info from MOSS profile service based on login.
        /// </summary>
        /// <param name="loginName">Name of the login.</param>
        /// <returns></returns>
        public PersonMetadata GetUserInfo(string loginName)
        {
            UserProfile userProfile = _userProfileManager.GetUserProfile(loginName);
            
            //Create JSON string for metadata to deserialize it
            StringBuilder metadataJSON = new StringBuilder(100);

            metadataJSON.Append("{");
            foreach (var item in _mapping.GetMapping())
            {
                //item.Key is PersonMetadata Property name
                //item.Value is Sharepoint 2007 User profile property name
                try
                {
                    var metadata = userProfile[item.Value].Value as string;
                    metadataJSON.AppendFormat(
                        "\"{0}\":\"{1}\",",
                        item.Key, //PersonMetadata Property name
                        string.IsNullOrEmpty(metadata) ? string.Empty : metadata); //metadata value
                }
                catch
                {
                    //Swallow exception and skip the property mapping.
                    //Should happen only, when property name is invalid.
                    continue;
                }
            }
            if (metadataJSON[metadataJSON.Length - 1] == ',')
                metadataJSON.Remove(metadataJSON.Length - 1, 1); //Remove last ",", it not needed. Remove is fast.
            metadataJSON.Append("}");

            PersonMetadata personMetadata =
                new JavaScriptSerializer().Deserialize<PersonMetadata>(metadataJSON.ToString());
            return personMetadata;
        }

        #endregion
    }
}
